package com.jh.user.business.impl;

import cn.jh.common.exception.ServiceException;
import com.jh.user.business.ThirdPayRateBusiness;
import com.jh.user.controller.model.ThirdPayRateRequest;
import com.jh.user.pojo.ThirdPayRate;
import com.jh.user.pojo.enums.ThirdPayType;
import com.jh.user.repository.ThirdPayRateRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Yichuan
 * @version 1.0
 */
@Service
public class ThirdPayRateBusinessImpl implements ThirdPayRateBusiness {

    private final static Logger LOGGER = LoggerFactory.getLogger(ThirdPayRateBusinessImpl.class);

    private final ThirdPayRateRepository thirdPayRateRepository;

    @Autowired
    public ThirdPayRateBusinessImpl(ThirdPayRateRepository thirdPayRateRepository) {
        this.thirdPayRateRepository = thirdPayRateRepository;
    }

    @Override
    public List<ThirdPayRate> findThirdPayRate(Long brandId) {
        return thirdPayRateRepository.findByBrandId(brandId);
    }

    public ThirdPayRate findByBrandIdAndThirdPayType(Long brandId ,ThirdPayType payType) {
        ThirdPayRateRequest thirdRequest = new ThirdPayRateRequest();
        ThirdPayRate thirdPayRate = thirdPayRateRepository.findThirdPayRate(brandId, payType);
        if (thirdPayRate == null) {
            thirdPayRate = ThirdPayRate.init(thirdRequest);
        }
        return thirdPayRate;
    }


    @Transactional
    @Override
    public ThirdPayRate updateThirdPayRate(ThirdPayRateRequest thirdRequest) throws ServiceException {
        ThirdPayRate thirdPayRate = thirdPayRateRepository.findThirdPayRate(thirdRequest.getBrandId(), thirdRequest.getPayType());
        if (thirdPayRate == null) {
            thirdPayRate = ThirdPayRate.init(thirdRequest);
        }
        thirdPayRate.setRangeList(thirdRequest.getRanges());
        thirdPayRate.setUpdatedAt(LocalDateTime.now());
        thirdPayRateRepository.saveAndFlush(thirdPayRate);
        return thirdPayRate;
    }


}
